package edu.ynu.e_platform.entities;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.Set;

/**
 * @author manwen Yang
 */
@Entity
@Getter
@Setter
@DiscriminatorValue("1")
@EntityListeners(AuditingEntityListener.class)  //监听实体的修改
public class Business extends User {

    @OneToMany(mappedBy = "business",
            fetch = FetchType.LAZY,
            orphanRemoval = true,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"business","shopItems","orders"})
    private Set<Shop> shops;

    @OneToMany(mappedBy = "business",
            fetch = FetchType.LAZY,
            orphanRemoval = true,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"business","lineItem","shopItems"})
    private Set<Item> items;


    /**
     *  商家创建门店,店铺名字要求唯一
     * @param shopName
     * @return shop 创建的店铺
     */
    @JsonIgnore
    public Shop createShop(String shopName){

        //查看店铺是否已创建
        for(Shop shop : shops){
            if(shop.getShopName().equals(shopName)){
                return shop;
            }
        }
        Shop shop = new Shop();
        shop.setShopName(shopName);
        shop.setBusiness(this);

        shops.add(shop);

        return shop;
    }

    /**
     *  商家创建门店,店铺名字要求唯一
     * @param newshop
     * @return shop
     */
    @JsonIgnore
    public Shop createShop(Shop newshop){

        //查看店铺是否已创建
        for(Shop shop : shops){
            if(shop.getShopName().equals(newshop.getShopName())){
                return shop;
            }
        }
        shops.add(newshop);

        return newshop;
    }

    /**
     *  商家创建属于自己的商品
     *  @param newItem
     * @return Item
     */
    @JsonIgnore
    public Item createItem(Item newItem){

        newItem.setBusiness(this);
        items.add(newItem);

        return newItem;
    }

    /**
     *  确认已支付的订单
     * @param order
     * @return order 完成确认的订单
     */
    @JsonIgnore
    public Order affirmOrder(Order order){

        //已支付的订单才允许确认
        if (order.getStatus().equals(1)){
            order.setStatus(2);
        }

        return order;
    }

    /**
     *  取消已支付的订单
     * @param order
     * @return order 取消的订单
     */
    @JsonIgnore
    public Order cancelOrder(Order order){

        //已支付的订单才允许取消
        if (order.getStatus().equals(1)){
            order.setStatus(2);
        }

        return order;
    }

}
